<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Manage extends CI_Controller {

    private $database = '';

    public function __construct()
    {
        parent::__construct();
        if (!$this->session->userdata('token'))
            redirect('login');
        date_default_timezone_set('PRC');
        header("Content-type: text/html; charset=utf-8");
        $this->load->database();
        $this->database = $this->db->database;
    }

    public function index($table='',$index=0){
        $this->input->set_cookie('url',current_url(),7200);

        if (!empty($table)) {

            $data['fields'] = $this->_get_table_fields($table);
            $per_page     = 10;
            
            if ($table=='member') {
                $sql = 'SELECT * FROM member WHERE username IS NOT NULL ORDER BY create_time DESC';
                $rows = $this->db->query($sql)->result_array();
                $data['rows'] = $rows;
                $count = count($rows);

            }else{
                $count        = $this->db->count_all($table);
                $rows         = $this->db->order_by("id","desc")->get("{$table}",$per_page ,$index)->result_array();
                $data['rows'] = $rows;
            }

            $this->load->library('pagination');
            $config['base_url']      = site_url("manage/index/{$table}/");
            $config['total_rows']    = $count;
            $config['per_page']      = $per_page ; //每页显示的数据数量
            $config['first_link']    = '首页';
            $config['last_link']     = '尾页';
            $config['prev_link']     = '上一页';
            $config['next_link']     = '下一页';
            $config['uri_segment']   = 4;
            $this->pagination->initialize($config);
            $pages = $this->pagination->create_links();
            $data['pages'] =  $pages;
        }
        $data['current_table'] = $table;
        $data['tables'] = $this->_get_tables();
        $this->load->view('index',$data);
    }

    private function _get_tables(){
        $sql    = "select TABLE_NAME,TABLE_COMMENT from INFORMATION_SCHEMA.TABLES where table_schema='{$this->database}'";
        $tables = $this->db->query($sql)->result_array();
        return $tables;
    }

    private function _get_table_fields($table = ''){
        $sql = "select COLUMN_NAME,column_comment from INFORMATION_SCHEMA.Columns where table_name='{$table}' and table_schema='{$this->database}'";
        $fileds = $this->db->query($sql)->result_array();
        return $fileds;
    }

    private function _get_current_table($table = ''){
        //todo
    }

    public function logout(){
        $this->session->unset_userdata('token');
        redirect('login');
    }

    public function delete($table_name='',$id='')
    {
        if(empty($table_name) || empty($id))
            exit("params error");
        $this->db->where('id', $id)->delete($table_name);
        header("Location:".$this->input->cookie('url'));
    }

    public function edit($table_name='',$id=0){

        #字段
        $fields = $this->_get_table_fields($table_name);

        #数据
        $query  = $query = $this->db->where("id",$id)->get($table_name);
        $row    = $query -> row_array();

        foreach ($fields as $key=>$field) {
            $fields[$key]['value'] = $row[$field['COLUMN_NAME']];
        }

        $html = $this->_form_bulder($table_name,$fields,'update');

        $data['html'] = $html ;
        $data['tables'] = $this->_get_tables();
        $data['current_table'] = $table_name;

        $this->load->view('edit',$data);
    }

    public function update(){
        $data       = $this->input->post(NULL);
        $id         = $data['id'];
        $table_name = $data['table_name'];

        unset($data['table_name']);
        unset($data['id']);

        $this->db->where('id', $id);
        $this->db->update($table_name, $data);
        header("Location:".$this->input->cookie('url'));
    }

    public function add($table_name){
        #字段
        $fields = $this->_get_table_fields($table_name);
        foreach ($fields as $key=>$field) {
            $fields[$key]['value'] = '';
        }
        $html = $this->_form_bulder($table_name,$fields,'save');
        $data['html'] = $html ;

        $data['tables'] = $this->_get_tables();
        $data['current_table'] = $table_name;
        $this->load->view('add',$data);
    }

    public function save(){
        $data       = $this->input->post(NULL);
        $id         = $data['id'];
        $table_name = $data['table_name'];

        unset($data['table_name']);
        unset($data['id']);
        $this->db->insert($table_name,$data);
        redirect("manage/index/{$table_name}");
    }


    private function _form_bulder($table_name,$fields,$action='update'){
        // '<form class="form-horizontal">'
        $html = form_open_multipart('manage/'.$action,array("class"=>"form-horizontal"));
        foreach ($fields as $field) {
            if (strpos($field['COLUMN_NAME'],"file")!==false) {
                $html .= $this->_file_input($field);
            }elseif(strpos($field['COLUMN_NAME'],"_id")!==false){
                $html .= $this->_form_foreign_key($field);
            }elseif(strpos($field['COLUMN_NAME'],"content")!==false){
                $html .= $this->_content_input($field,$action);
            }else{
                $html .= $this->_common_input($field);
            }
        }

        $html .= '<div class="form-group">';
        $html .=      '<div class="col-sm-offset-2 col-sm-10">';
        $html .=              '<button type="submit" class="btn btn-default">提交</button>';
        $html .=            '</div>';
        $html .=        '</div>';
        $html .= '<input name="table_name" type="hidden" value="'.$table_name.'"/>';
        $html .= '</form>';
        return $html;
    }

    private function _content_input($field,$action){
        $html = '<div class="form-group">';
        $html .=     '<label class="col-sm-2 control-label ">'.$field['column_comment'].'</label>';
        $html .=     '<div class="col-sm-9">';

        if ($action=='save') {
            $html .=         '<textarea class="form-control" rows="8" name="'.$field['COLUMN_NAME'].'" id="'.$field['COLUMN_NAME'].'">'.$field['value'].'<p>此标签中写内容</p></textarea>';
        }else{
            $html .=         '<textarea class="form-control" rows="8" name="'.$field['COLUMN_NAME'].'" id="'.$field['COLUMN_NAME'].'">'.$field['value'].'</textarea>';
        }

        $html .=     '</div>';
        $html .= '</div>';
        return $html;
    }

    private function _common_input($field){

        $style = ($field['COLUMN_NAME']=='id')?'readOnly="true"':'';

        $html = '<div class="form-group">';
        $html .=     '<label class="col-sm-2 control-label ">'.$field['column_comment'].'</label>';
        $html .=     '<div class="col-sm-9">';
        $html .=         '<input type="text" class="form-control " '.$style.' name="'.$field['COLUMN_NAME'].'" id="'.$field['COLUMN_NAME'].'" value="'.$field['value'].'">';
        $html .=     '</div>';
        $html .= '</div>';
        return $html;
    }

    private function _file_input($field){

        $html = '<div class="form-group">';
        $html .=         '<label class="col-sm-2 control-label">'.$field['column_comment'].'</label>';
        $html .=        '<div class="col-sm-9">';
        $html .=            '<div class="input-group">';
        $html .=                '<input  type="text"  name="'.$field['COLUMN_NAME'].'" class="form-control '.$field['COLUMN_NAME'].' " value="'.$field['value'].'">';
        $html .=                '<input onchange="fileSelected(this,this.id);" class="btn btn-primary " type="file" id="'.$field['COLUMN_NAME'].'"  class="form-control" value="'.$field['value'].'">';
        // $html .=                '<span class="input-group-btn">';
        // $html .=                    '<a class="btn btn-primary iframe-btn" data="'.$field['COLUMN_NAME'].'"> 选择附件</a>';
        // $html .=                '</span>';
        $html .=            '</div>';
        $html .=        '</div>';
        $html .= '</div>';
        return $html;
    }

    private function _form_foreign_key($field){
        $table_name = substr ($field['COLUMN_NAME'],0, strripos($field['COLUMN_NAME'],"_id"));

        $this->db->select('id,name');
        $this->db->order_by("id","desc");
        $query = $this->db->get($table_name)->result_array();

        $html = '<div class="form-group"><label class="col-sm-2 control-label">'.$field['column_comment'].'</label><div class="col-sm-9"><select class="form-control" name="'.$field['COLUMN_NAME'].'">';
        foreach ($query as $key => $item) {
            $style = ($item['id']==$field['value'])?'selected="selected"':'';
            $html .= '<option '.$style.' value="'.$item['id'].'">'.$item['name'].'</option>';
        }

        $html .= '</select></div></div>';
        return $html ;
    }

    // public function to_upload($column=0)
    // {
    //     $this->load->view('upload_form', array('error' => '','column'=>$column));
    // }

    public function do_upload(){

        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = '*';
        $config['encrypt_name'] = TRUE;

        $this->load->library('upload', $config);

        if ( ! $this->upload->do_upload('userfile'))
        {
            var_dump($this->upload->display_errors());
        }
        else
        {
            $datas = $this->upload->data();
            $data['file']   = $datas['file_name'];
            echo json_encode(array('imagePath'=>$data['file'],'status'=>'success'));

            // $data['column'] = $column;
            // $this->load->view('upload_success',$data);
        }
    }
}
